package EGS.impl;
import java.util.List;
import java.util.concurrent.ExecutorService;

import javax.swing.JTable;

import org.dom4j.Document;
import org.dom4j.Element;

import com.google.gson.Gson;

import TOOLS.SQLtool;
import TOOLS.errCodeManagement;
import WORKPLACE.URLapi;
import WORKPLACE.stationClient;

public class EGS_execute_service501Impl{
	public boolean isUnknowCase = false;
	ExecutorService iExecutorService;
	Document MSG;
	boolean isPanel = false;
	stationClient iClient=null;
	SQLtool sql = null;

	/**
	 * 卡前站 1、获取工位工序 2、查询条码卡前站情况 2.1、未注册条码异常：查询工位当前工单及其工艺，如果是前工序都是非必过站，进行工单注册
	 */
	public EGS_execute_service501Impl(stationClient nClient, Document MSG_in, ExecutorService executorService, 
			SQLtool goldenSql) throws Exception {
		super();
		sql=goldenSql;
		if(nClient!=null) {
			iClient=nClient;
		}else {
			iClient=null;
		}
		MSG = MSG_in;
		iExecutorService = executorService;
	}

	public Document runCal() {
		if (MSG == null) {
			return null;
		}
		Element Mroot = MSG.getRootElement();
		Element eleR = Mroot.element("body").addElement("result");
		try {
//			String transactionID = Mroot.element("header").attribute("transactionID").getValue();
//			eleR.addAttribute("actionCode", transactionID);//部分设备需要 <result errorCode=
			String iStation = Mroot.element("header").element("location").attribute("equipmentName").getValue();
			if(iClient==null) {
				throw new Exception("工位信息获取失败");
			}
			String msgClass = Mroot.element("header").attribute("messageClass").getValue();
			if (!(msgClass.equals("501")) && !(msgClass.equals("5018"))) {
				throw new Exception("实现类用错:"+this.getClass().getName());
			}
			List<?> pcbs =Mroot.element("body").elements("pcb");
			if(pcbs!=null && pcbs.size()>0) {
				for(int i=0;i<pcbs.size();i++) {
					calBody((Element) pcbs.get(i),iStation,msgClass);
					Mroot.element("body").remove((Element)pcbs.get(i));
				}
			}

			eleR.addAttribute("errorCode", "0");
			eleR.addAttribute("errorText", "");
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						URLapi aa=new URLapi();//将501作为有板监控
						aa.RESTInvoker("http://192.168.0.220:8081", "","");
						StationAddress poster=new StationAddress();
						poster.ipAddress=iStation;
						poster.state="1";
						String ijson=new Gson().toJson(poster);
						aa.postDataToServer("/api/alarm/smtState", ijson);
					} catch (Exception e) {
						AKSLogs(250604,"501("+iStation+")有板监控异常："+e.getMessage());
					}
				}

			}).start();
			
			
		} catch (Exception e) {
			String str = errCodeManagement.getErrText(e.getMessage());
			System.out.println(str);
			eleR.addAttribute("errorCode", "1");
			eleR.addAttribute("errorText", str);
		}

		return MSG;
	}
	
	public void calBody(Element pcb,String iStation, String msgClass) throws Exception {
		int iiLayer;

		String iSN =pcb.attribute("barcode").getValue();
		String iLayer =pcb.attribute("pcbSide").getValue();
		String isPanel="-1";
		try {
			isPanel = pcb.attribute("isPanel").getValue();
		}catch(Exception ee) {
			isPanel="-1";
		}
		String procedure="-1";
		try {
			procedure =pcb.attribute("procedureNumber").getValue();
			if(procedure.length()<1) {
				procedure="-1";
			}
		}catch(Exception ee) {
			procedure="-1";
		}
		iiLayer = Integer.parseInt(iLayer);
		try {
			if(iiLayer==-1) {
				iiLayer=iClient.myLayer;
			}
			if (iiLayer != iClient.myLayer) {
				String str = iStation + "工单激活面别("+iClient.myLayer+")与产品上传面别不一致！";
				AKSLogs(Integer.parseInt(msgClass + "0"), "" + iSN + "_" + iStation + "_" + iLayer + "_" + str);
				throw new Exception(str);
			} else {
				boolean result = iClient.checkWIPpermmision(iSN,isPanel,procedure); 
				String errorText;
				if (result) {
					if (iClient.myProcedureNumber.equals("A0200")) {// 检查是否有标签，等何工布置后解除屏蔽
						String iLab = sql.selectFirstValue("select label from history_snLabel where state=1 "
								+ "and serialNumber='" + iSN + "'");
						if ((iLab != null) && (!iLab.equals(iSN))) {
							String sss="select os.serialNumber,ll.labelPart,ll.autoLabel from dbo.vOrderSerialNumber os \r\n" + 
									"LEFT JOIN dbo.vOrderList_new op ON op.orderNumber=os.orderNumber \r\n" + 
									"left JOIN dbo.vOrderList_new om ON om.orderNumber=op.masterOrderNumber\r\n" + 
									"LEFT JOIN Label.LabelList ll ON ll.LabelPart=om.partNumber and ll.autoLabel=2\r\n" + 
									"where os.serialNumber='"+iSN+"' and ll.autoLabel=2 ";
							JTable t=sql.select(sss);//标签如果没有二维码，不必强制扫描二维码
							if(t==null || t.getRowCount()<1) {
								errorText = iSN + "此产品全检要求扫描产品标签";
								result = false;
								throw new Exception(errorText);
							}
						}
					}
				} else {
					errorText = iSN + "前工序异常";
					throw new Exception(errorText);
				}
				AKSLogs(Integer.parseInt(msgClass + "1"),
						"" + iSN + "_" + iStation + "_" + iLayer + "_" + result);
			}
		} catch (Exception e) {
			String str = errCodeManagement.getErrText(e.getMessage());
			if (e.getMessage().equals("-152")) {
				try {
					String realSN = iClient.getSN4Label(iSN);// 如果条码未识别，先查询看看是否为标签
					if (realSN != null) {
						try {
							boolean result = iClient.checkWIPpermmision(realSN,isPanel,procedure);
							if (!result) {
								String errorText = iSN + "前工序异常";
								throw new Exception(errorText);
							}
							AKSLogs(Integer.parseInt(msgClass + "1"), "" + iSN + "_" + iStation + "_" + iLayer);
						} catch (Exception e1) {
							String errorText = iSN + "_" + errCodeManagement.getErrText(e1.getMessage());
							AKSLogs(Integer.parseInt(msgClass + "0"),
									"" + iSN + "_" + iStation + "_" + iLayer + "_" + errorText);
							throw new Exception(errorText);
						}
					} else {
						String errorText = iSN + "_条码不存在";
						AKSLogs(Integer.parseInt(msgClass + "0"),
								"" + iSN + "_" + iStation + "_" + iLayer + "_" + errorText);
						throw new Exception(errorText);
					}
				} catch (Exception e1) {
					String errorText = iSN + "_" + errCodeManagement.getErrText(e1.getMessage());
					AKSLogs(Integer.parseInt(msgClass + "0"),
							"" + iSN + "_" + iStation + "_" + iLayer + "_" + errorText);
					throw new Exception(errorText);
				}
			} else {
				str=e.getMessage();
				String [] sstr=e.getMessage().split("@");
				if(sstr[0].equals("-153")) {
					str=iSN + "_" + sstr[1]
					+"_工位工单="+iClient.activeOrderNumber;
				}else {
					str = iSN + "_" + errCodeManagement.getErrText(e.getMessage());
				}
				AKSLogs(Integer.parseInt(msgClass + "0"), "" + iSN + "_" + iStation + "_" + iLayer + "_" + str);
				throw new Exception(str);
			}
		}
			

	}

	public void AKSLogs(int iType, String ilogClientNews) {
		SQLtool.AKSLogs(iType, ilogClientNews);
	}

}
